import ProCard from '@ant-design/pro-card';
import styles from '@/pages/market/Item/index.less';
import React from 'react';
import { Button } from 'antd';
import moment from 'moment';
import { ModalForm, ProFormDigit, ProFormText } from '@ant-design/pro-form';
import { useModel } from '@@/plugin-model/useModel';

const AuctionFormCard = ()=>{
  // 全局变量
  const { initialState } = useModel('@@initialState');

  if(!initialState){
    return <div/>
  }
  // 页面变量
  const {item,owner,approved,tokenId,loading} = useModel('item');
  const { currentAccount,provider,contracts:{auctionContract} } = initialState;

  if(!item){
    return <div/>
  }

  if(currentAccount?.address!==owner){
    return <div/>
  }

  if(owner==auctionContract.address){
    return <div/>
  }

  if(approved!==auctionContract.address){
    return <div/>
  }

  return (
    <ProCard className={styles.itemCard} headerBordered bordered title="操作" loading={loading}>
      <ModalForm
        title="设置价格"
        trigger={<Button type="primary">拍卖出售</Button>}
        onFinish={async (values) => {
          values.duration = moment.duration(values.duration, 'hours').asSeconds();
          try {
            const signer = await provider.getSigner();
            const overrides = {
              from: await signer.getAddress(),
              gasPrice: await provider.getGasPrice(),
              gasLimit: 500000,
              nonce: await signer.getTransactionCount(),
            };

            console.log(values.duration)
            // 预执行合约
            console.log(await auctionContract.callStatic.create(
              tokenId,
              values.price,
              values.duration,
              overrides,
            ));
            // 实际执行合约
            const tx = await auctionContract
              .connect(signer)
              .create(
                tokenId,
                values.price,
                values.duration,
                overrides,
              );
            await tx.wait();
            window.location.reload();
          } catch (e) {
            console.error(e);
          }
          return true;
        }}
      >
        <ProFormText
          name="price"
          label="起拍价"
          placeholder="金额"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormDigit
          name="duration"
          label="持续时间"
          placeholder="持续时间"
          rules={[
            {
              required: true,
            },
          ]}
        />
      </ModalForm>
    </ProCard>
  );
}

export default AuctionFormCard
